<template>
  <div v-loading="isLoading">
    <el-form label-width="100">
      <el-form-item label="SKU名称">
        <el-input
          v-model="skuData.skuName"
          placeholder="请输入名称"
          clearable
        ></el-input>
      </el-form-item>
      <el-form-item label="价格(元)">
        <el-input
          v-model="skuData.price"
          placeholder="请输入价格"
          clearable
          type="number"
        ></el-input>
      </el-form-item>
      <el-form-item label="重量(g)">
        <el-input
          v-model="skuData.weight"
          placeholder="请输入重量"
          clearable
          type="number"
        ></el-input>
      </el-form-item>
      <el-form-item label="描述">
        <el-input
          v-model="skuData.skuDesc"
          placeholder="SKU描述"
          type="textarea"
        ></el-input>
      </el-form-item>
      <el-form-item label="平台属性">
        <el-form inline label-width="100">
          <el-form-item :label="i.attrName" v-for="i in attrList" :key="i.id">
            <el-select v-model="i.attrKeyAndValue">
              <el-option
                :value="`${i.id}:${v.id}`"
                v-for="v in i.attrValueList"
                :label="v.valueName"
                :key="v.id"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-form>
      </el-form-item>
      <el-form-item label="销售属性">
        <el-form inline label-width="100">
          <el-form-item
            :label="i.saleAttrName"
            v-for="i in saleList"
            :key="i.id"
          >
            <el-select v-model="i.saleKeyAndValue">
              <el-option
                :value="`${i.id}:${v.id}`"
                v-for="v in i.spuSaleAttrValueList"
                :label="v.saleAttrValueName"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-form>
      </el-form-item>
      <el-form-item label="展示图片">
        <el-table border :data="imgList" ref="tableRef">
          <el-table-column type="selection" width="55" />
          <el-table-column label="图片">
            <template #="{ row }">
              <img width="200" :src="row.imgUrl" :alt="row.imgName" />
            </template>
          </el-table-column>
          <el-table-column prop="imgName" label="名称"></el-table-column>
          <el-table-column label="操作" width="150">
            <template #="{ row }">
              <el-button
                :type="
                  skuData.skuDefaultImg == row.imgUrl ? 'success' : 'warning'
                "
                @click="setImg(row)"
                >设为默认图</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>
      <el-form-item>
        <el-button :loading="btnLoading" type="primary" @click="submitSkuData"
          >提交</el-button
        >
        <el-button @click="cancel">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup lang="ts">
import useCategoryStore from "@/store/modules/category";
import { reqattrInfoList } from "@/api/product/attr";
import {
  spuImageList,
  reqspuSaleAttrList,
  reqsaveSkuInfo,
} from "@/api/product/sku";
import { reactive, ref } from "vue";
import { ElNotification } from "element-plus";

const $emits = defineEmits(["returnVc"]);
let categoryStore = useCategoryStore();
let attrList = ref<any>([]);
let saleList = ref<any>([]);
let imgList = ref<any>([]);
let isLoading = ref<boolean>(false);
let btnLoading = ref<boolean>(false);
let tableRef = ref();

// 收集表单数据
let skuData = reactive<any>({
  category3Id: 0,
  spuId: 0,
  tmId: 0,
  skuName: "",
  price: null,
  weight: null,
  skuDesc: "",
  skuAttrValueList: [], //{attrId,valueId}
  skuSaleAttrValueList: [], //{saleAttrId,saleAttrValueId}
  skuDefaultImg: "", //图片地址
});

//页面初始化，由父组件通知调用
const skuFormInit = async (spu: any) => {
  isLoading.value = true;
  // 每次初始化先清空数据
  clearData();
  // 获取平台属性
  attrList.value = (
    await reqattrInfoList(
      categoryStore.chooseCategory[0],
      categoryStore.chooseCategory[1],
      categoryStore.chooseCategory[2],
    )
  ).data;
  // 获取销售属性
  saleList.value = (await reqspuSaleAttrList(spu.id)).data;
  // 获取图片列表
  imgList.value = (await spuImageList(spu.id)).data;
  // 初始化给sku数据赋值
  skuData.category3Id = categoryStore.chooseCategory[2];
  skuData.spuId = spu.id;
  skuData.tmId = spu.tmId;
  isLoading.value = false;
};
defineExpose({
  skuFormInit,
});

//取消返回上一页
const cancel = () => {
  //通知父组件切换
  $emits("returnVc");
};

//当设置默认图片时
const setImg = (imgRow: any) => {
  skuData.skuDefaultImg = imgRow.imgUrl;
  tableRef.value.clearSelection();
  tableRef.value.toggleRowSelection(imgRow, true);
};

//收集完成数据提交数据
const submitSkuData = async () => {
  btnLoading.value = true;
  //发送请求前，要处理平台属性和销售属性的数据格式，整理为接口所需要格式
  // attrList.value.forEach((item: any) => {
  //   if (item.attrKeyAndValue) {
  //     let kvAtt = item.attrKeyAndValue.split(':')
  //     skuData.skuAttrValueList.push({
  //       attrId: kvAtt[0],
  //       valueId: kvAtt[1]
  //     })
  //   }
  // })

  // 改用reduce可以避免skuData数据在当前组件中多次提交下重复push问题
  skuData.skuAttrValueList = attrList.value.reduce((prev: any, item: any) => {
    if (item.attrKeyAndValue) {
      let [attrId, valueId] = item.attrKeyAndValue.split(":");
      prev.push({ attrId, valueId });
    }
    return prev;
  }, []);
  skuData.skuSaleAttrValueList = saleList.value.reduce(
    (prev: any, item: any) => {
      if (item.saleKeyAndValue) {
        let [saleAttrId, saleAttrValueId] = item.saleKeyAndValue.split(":");
        prev.push({ saleAttrId, saleAttrValueId });
      }
      return prev;
    },
    [],
  );

  //提交数据给接口
  let result = await reqsaveSkuInfo(skuData);
  if (result.code == 200) {
    ElNotification.success("添加成功");
    $emits("returnVc");
  } else {
    ElNotification.error("添加失败");
    //添加失败不返回，但要清除skuData中平台属性和销售属性的数组，否则再次提交会push相同数据,但这里处理函数改成reduce解决了该问题，因此不需清除
    // skuData.skuAttrValueList = [];
    // skuData.skuSaleAttrValueList = [];
  }
  btnLoading.value = false;
};

//数据清理
const clearData = () => {
  attrList.value = [];
  saleList.value = [];
  imgList.value = [];
  Object.assign(
    skuData,
    JSON.parse(
      JSON.stringify({
        category3Id: 0,
        spuId: 0,
        tmId: 0,
        skuName: "",
        price: null,
        weight: null,
        skuDesc: "",
        skuAttrValueList: [], //{attrId,valueId}
        skuSaleAttrValueList: [], //{saleAttrId,saleAttrValueId}
        skuDefaultImg: "", //图片地址
      }),
    ),
  );
};
</script>

<style scoped></style>
